package com.yt.user.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.db.utils.RedisTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.user.models.service.ILoginInfoService;
import com.yt.user.models.bo.LoginInfoBO;
import com.yt.user.models.dto.LoginInfoDTO;

/**
 * 登录控制器
 *
 * @author xieyanfei
 * @Date 2025-09-05 18:01:58
 */

@RestController
@RequestMapping("/api/loginInfo")
@Slf4j
@Api(value = "LoginInfoApiController",tags = "登录Api接口")
public class LoginInfoApiController {

    @DubboReference
    private ILoginInfoService loginInfoService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<LoginInfoDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        LoginInfoDTO dto = loginInfoService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "登录列表",notes = "登录列表")
    @PostMapping("/queryPageList")
    public Result<Page<LoginInfoDTO>> queryPageList(LoginInfoBO bo){
        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<LoginInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = loginInfoService.selectPage(page, wrapper);

        return new Result<>(page);
    }
    @Autowired
    private RedisTokenUtil redisTokenUtil;
    // 修改文件: yt-user/yt-user-server/src/main/java/com/yt/user/api/client/LoginInfoApiController.java
//    @PostMapping("/login")
//    @ApiOperation(value = "用户登录", notes = "用户登录获取token")
//    public Result<String> login(@RequestParam String account, @RequestParam String password) {
//        // 查询用户信息
//        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
//        wrapper.eq("account", account);
//        LoginInfoDTO loginInfo = loginInfoService.selectOne(wrapper);
//
//        if (loginInfo == null) {
//            return new Result<>(CodeEnum.FAIL_100003, "账号不存在");
//        }
//
//        // 验证密码(实际项目中应该用加密方式验证)
//        if (!loginInfo.getPassword().equals(password)) {
//            return new Result<>(CodeEnum.FAIL_100003, "密码错误");
//        }
//
//        // 验证账号状态
//        if (loginInfo.getStatus() == 0) {
//            return new Result<>(CodeEnum.FAIL_100003, "账号已禁用");
//        }
//
//        // 生成token
//        String token = redisTokenUtil.generateToken(loginInfo.getUserId());
//        return new Result<>(token);
//    }
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录获取token")
    public Result<String> login(@RequestParam String account, @RequestParam String password) {
        // 查询用户信息（日志显示此步骤已成功）
        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("account", account);
        LoginInfoDTO loginInfo = loginInfoService.selectOne(wrapper);

        if (loginInfo == null) {
            return new Result<>(CodeEnum.FAIL_100003, "账号不存在");
        }

        // 修复：使用盐值+加密算法验证密码（示例为MD5加密）
        String salt = loginInfo.getSalt(); // 从数据库获取盐值
        // 加密规则：MD5(明文密码 + 盐值)
        String encryptedPassword = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!loginInfo.getPassword().equals(encryptedPassword)) {
            return new Result<>(CodeEnum.FAIL_100003, "密码错误");
        }

        // 验证账号状态（已有逻辑）
        if (loginInfo.getStatus() == 0) {
            return new Result<>(CodeEnum.FAIL_100003, "账号已禁用");
        }

        // 生成token（已有逻辑）
        String token = redisTokenUtil.generateToken(loginInfo.getUserId());
        return new Result<>(token);
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户登出", notes = "用户登出删除token")
    public Result logout(@RequestHeader("Token") String token) {
        if (token == null || !redisTokenUtil.isTokenValid(token)) {
            return new Result<>(CodeEnum.FAIL_100004, "无效的token");
        }

        redisTokenUtil.deleteToken(token);
        return new Result<>();
    }
}
